import {isSystemOrExtensionUrl} from '@/lib/utils';
import {chromeTabs, chromeWindows, chromeActions} from '@/lib/chromeApi';
import {queryClient} from '@/lib/queryClient';
import * as tabsApi from '@/api/tabs';
import type {CaptureTabsRequest, CaptureTabItem} from '@/api/types';

/**
 * 保存当前窗口为集合并关闭对应标签页
 */
export async function saveCurrentWindowAsCollection(
    spaceId: number,
    name?: string,
    defaultNamePrefix?: string,
): Promise<{ savedTabIds: number[] }> {
    const tabs = await chromeActions.getCurrentWindowTabs();

    const captureItems: CaptureTabItem[] = [];
    const nonPinnedTabIds: number[] = [];
    let pinnedTabsCount = 0;

    for (const tab of tabs) {
        if (tab.pinned) {
            pinnedTabsCount += 1;
            continue;
        }

        if (!tab.url) continue;

        const isSystemTab = isSystemOrExtensionUrl(tab.url);
        if (!isSystemTab) {
            captureItems.push({
                url: tab.url,
                title: tab.title ?? tab.url,
                favicon: tab.favIconUrl && /^https?:/i.test(tab.favIconUrl) ? tab.favIconUrl : undefined,
                is_pin: false,
            });
        }

        if (typeof tab.id === 'number') {
            nonPinnedTabIds.push(tab.id);
        }
    }

    if (captureItems.length === 0) {
        return { savedTabIds: [] };
    }

    const defaultName = `${defaultNamePrefix || '标签于'} ${new Date().toLocaleString()}`;
    const request: CaptureTabsRequest = {
        space_id: spaceId,
        collection_name: name?.trim() || defaultName,
        tabs: captureItems,
    };

    await tabsApi.captureTabs(request);

    // 失效该空间的集合缓存，触发重新获取
    await queryClient.invalidateQueries({
        queryKey: ['spaces', spaceId, 'collections'],
    });

    const result = await chromeActions.saveCollectionAndManageTabs(nonPinnedTabIds, pinnedTabsCount);
    if (!result.success) {
        console.warn('标签页管理失败:', result.error);
    }

    return {savedTabIds: nonPinnedTabIds};
}

/**
 * 智能打开集合：根据当前窗口状态决定复用或新建窗口
 */
export async function openCollectionSmart(collectionId: number): Promise<void> {
    // 从缓存中获取集合数据
    let collection = null;

    // 遍历所有 collections 查询缓存，找到包含该集合的数据
    const queriesData = queryClient.getQueriesData({
        predicate: (query) =>
            query.queryKey[0] === 'spaces' &&
            query.queryKey[2] === 'collections',
    });

    for (const [, data] of queriesData) {
        if (Array.isArray(data)) {
            const found = data.find((dto: any) => dto.collection.id === collectionId);
            if (found) {
                // 转换为 SpaceCollection 格式
                collection = {
                    tabs: found.items.map((item: any) => ({
                        url: item.url,
                    })),
                };
                break;
            }
        }
    }

    if (!collection || collection.tabs.length === 0) {
        throw new Error('集合不存在或已被删除');
    }

    const urls = collection.tabs.map((tab: { url: string }) => tab.url);

    const isMinimal = await chromeActions.isCurrentWindowMinimal();
    if (isMinimal) {
        const currentWindow = await chromeWindows.getCurrent();
        for (const url of urls) {
            await chromeTabs.create({
                windowId: currentWindow.id,
                url,
                active: false,
            });
        }
        return;
    }

    await chromeWindows.create({url: urls});
}
